package com.atguigui.gulimall.cart.interceptor;

import com.atguigu.common.vo.MemberEntity;
import com.atguigui.gulimall.cart.constant.CartConstant;
import com.atguigui.gulimall.cart.vo.UserInfo;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

@Component
public class CartInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<UserInfo> threadLocal = new ThreadLocal<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserInfo userInfo = new UserInfo();
        //是否登录
        MemberEntity memberEntity= (MemberEntity) request.getSession().getAttribute(CartConstant.SPRING_SESSION_REDIS_KEY);
        if(memberEntity!=null){
            userInfo.setUserId(memberEntity.getId().toString());
        }
        //遍历所有的cookie
        Cookie[] cookies = request.getCookies();
        if(cookies!=null && cookies.length>0){
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals(CartConstant.CART_TEMP_USER_COOKIE_KEY)){
                    userInfo.setUserKey(cookie.getValue());
                    userInfo.setTemp(true);
                }
            }
        }
        //如果没有临时用户，创建一个临时用户
        if (userInfo.getUserKey()==null) {
            String userKey = UUID.randomUUID().toString();
            userInfo.setUserKey(userKey);
        }
        threadLocal.set(userInfo);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserInfo userInfo = threadLocal.get();
        if(!userInfo.isTemp()){
            Cookie cookie = new Cookie(CartConstant.CART_TEMP_USER_COOKIE_KEY,userInfo.getUserKey());
            cookie.setDomain("gulimall.com");
            //设置过期时间
            cookie.setMaxAge(CartConstant.COOKIE_USER_KEY_MAX);
            response.addCookie(cookie);
        }
    }
}
